package repositories

import (
    "SmartSearch/internal/models"
    "SmartSearch/internal/responses"
    "SmartSearch/pkg/database"
    "fmt"
    "time"
)

type UserRepository struct {
}

func (u *UserRepository) Add(user *models.User) error {
    user.CreatedDate = time.Now()
    user.UpdatedDate = time.Now()
    return database.DB.Create(&user).Error
}

func (u *UserRepository) FindByUsername(username string) *models.User {
    var user *models.User
    if err := database.DB.Where("username = ?", username).First(&user).Error; err != nil {
        return nil
    }
    return user
}

func (u *UserRepository) FindById(id int64) *models.User {
    var user *models.User
    if err := database.DB.Where("id = ?", id).First(&user).Error; err != nil {
        return nil
    }
    return user
}

func (u *UserRepository) Del(id int64) error {
    return database.DB.Delete(&models.User{}, id).Error
}

func (u *UserRepository) GetList(username string, departmentId *int64, phone string, name string, enable *bool, current int32, pageSize int32) interface{} {
    var total int64
    var data []*models.User
    where := fmt.Sprintf("username LIKE '%s'", "%"+username+"%")
    if departmentId != nil {
        where += fmt.Sprintf(" AND department_id = %d", *departmentId)
    }
    where += fmt.Sprintf("name LIKE '%s'", "%"+name+"%")
    where += fmt.Sprintf("phone LIKE '%s'", "%"+phone+"%")
    if enable != nil {
        where += fmt.Sprintf(" AND enable = %t", *enable)
    }
    // 此处用了PostForm的请求方法
    tx := database.DB.Debug().Model(models.User{}).Where(where) // 查询对应的数据库表
    // 此时的total是查询到的总数
    if err := tx.Count(&total).Error; err != nil {
        fmt.Println("获取总数错误" + err.Error())
        return nil
    }
    offset := (current - 1) * pageSize
    if err := tx.Order("id DESC").Offset(int(offset)).Limit(int(pageSize)).Find(&data).Error; err != nil {
        return nil
    }
    return &responses.Page{
        Current:  current,
        PageSize: pageSize,
        Total:    total,
        Content:  data,
    }
}

func (u *UserRepository) Update(user *models.User) error {
    user.UpdatedDate = time.Now()
    return database.DB.Save(&user).Error
}
